package com.fj.netty.eventloop;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

import java.nio.charset.Charset;

/**
 * @author fj
 * @date 2024/1/2 14:59
 */
public class EventLoopServer {
    public static void main(String[] args) {
        new ServerBootstrap()
                //第一个处理channel连接请求，第二个处理childChannel读写请求
                .group(new NioEventLoopGroup(), new NioEventLoopGroup(2))
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new ChannelInboundHandlerAdapter(){
                            @Override
                            public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                                String message = ((ByteBuf) msg).toString(Charset.defaultCharset());
                                System.out.println("收到消息："+ message);
                                super.channelRead(ctx, msg);
                            }
                        });
                    }
                }).bind(6789);
    }
}
